using System;
using System.IO;
using System.Threading.Tasks;
using System.Collections.ObjectModel;

namespace AvalonEditDemo.Models
{
    /// <summary>
    /// 表示一个文档的信息，包括内容、路径和状态
    /// </summary>
    public class DocumentInfo
    {
        /// <summary>
        /// 获取或设置文档的文件路径
        /// </summary>
        public string FilePath { get; set; }
        
        /// <summary>
        /// 获取或设置文档的内容
        /// </summary>
        public string Content { get; set; }
        
        /// <summary>
        /// 获取或设置文档是否已被修改且未保存
        /// </summary>
        public bool IsDirty { get; set; }
        
        /// <summary>
        /// 获取或设置文档是否为未命名文档（没有关联文件）
        /// </summary>
        public bool IsUntitled { get; set; }

        /// <summary>
        /// 获取文档的文件名
        /// 如果是未命名文档则返回"Untitled"，否则返回文件路径的文件名部分
        /// </summary>
        public string FileName => IsUntitled 
            ? "Untitled" 
            : Path.GetFileName(FilePath);

        /// <summary>
        /// 初始化DocumentInfo的新实例
        /// </summary>
        /// <param name="content">文档的初始内容</param>
        /// <param name="filePath">文档的文件路径，如果为null则创建未命名文档</param>
        public DocumentInfo(string content = "", string filePath = null)
        {
            Content = content;
            FilePath = filePath;
            IsUntitled = string.IsNullOrEmpty(filePath);
            IsDirty = IsUntitled;
        }
    }

    /// <summary>
    /// 管理编辑器的文档集合，提供打开、保存、关闭文档的功能
    /// </summary>
    public class DocumentManager
    {
        /// <summary>
        /// 获取所有打开的文档集合
        /// </summary>
        public ObservableCollection<DocumentInfo> OpenDocuments { get; } = new();
        
        /// <summary>
        /// 获取或设置当前活动的文档
        /// </summary>
        public DocumentInfo ActiveDocument { get; set; }

        /// <summary>
        /// 初始化DocumentManager的新实例
        /// 创建一个默认的新文档
        /// </summary>
        public DocumentManager()
        {
            NewDocument();
        }

        /// <summary>
        /// 创建一个新的空白文档并将其设为活动文档
        /// </summary>
        /// <returns>新创建的文档对象</returns>
        public DocumentInfo NewDocument()
        {
            var document = new DocumentInfo("# New Python Script\n\n", null);
            OpenDocuments.Add(document);
            ActiveDocument = document;
            return document;
        }

        /// <summary>
        /// 异步打开指定路径的文件
        /// 如果文件已经打开，则将其设为活动文档而不重新加载
        /// </summary>
        /// <param name="filePath">要打开的文件路径</param>
        /// <returns>表示文件的文档对象</returns>
        /// <exception cref="FileNotFoundException">当指定的文件不存在时抛出</exception>
        public async Task<DocumentInfo> OpenFileAsync(string filePath)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException($"File not found: {filePath}");

            // 检查文件是否已经打开
            foreach (var doc in OpenDocuments)
            {
                if (doc.FilePath == filePath)
                {
                    ActiveDocument = doc;
                    return doc;
                }
            }

            var content = await File.ReadAllTextAsync(filePath);
            var document = new DocumentInfo(content, filePath);
            OpenDocuments.Add(document);
            ActiveDocument = document;
            return document;
        }

        /// <summary>
        /// 异步保存文档到指定路径
        /// </summary>
        /// <param name="document">要保存的文档</param>
        /// <param name="filePath">保存的目标路径，如果为null则使用文档的当前路径</param>
        /// <returns>保存操作是否成功</returns>
        public async Task<bool> SaveDocumentAsync(DocumentInfo document, string filePath = null)
        {
            if (document == null)
                return false;

            if (filePath != null)
            {
                document.FilePath = filePath;
                document.IsUntitled = false;
            }
            else if (document.IsUntitled)
            {
                return false; // 需要文件路径
            }

            try
            {
                await File.WriteAllTextAsync(document.FilePath, document.Content);
                document.IsDirty = false;
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 关闭指定的文档
        /// 如果关闭的是当前活动文档，则将其他文档设为活动文档，或创建新文档
        /// </summary>
        /// <param name="document">要关闭的文档</param>
        public void CloseDocument(DocumentInfo document)
        {
            if (document == null)
                return;

            OpenDocuments.Remove(document);

            if (ActiveDocument == document)
            {
                ActiveDocument = OpenDocuments.Count > 0 
                    ? OpenDocuments[0] 
                    : NewDocument();
            }
        }

        /// <summary>
        /// 将文档标记为已修改状态
        /// </summary>
        /// <param name="document">要标记的文档</param>
        public void MarkDocumentDirty(DocumentInfo document)
        {
            if (document != null)
                document.IsDirty = true;
        }
    }
} 